package org.iblink.gui.swing.views.component;

import java.awt.event.ActionListener;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.border.TitledBorder;

import org.iblink.gui.swing.actions.CategoryAction;

/**
 * Context menu to manage categories in a category tree
 * 
 * @author tpares
 *
 */
public class CategoryPopupMenu extends JPopupMenu {
  /**
   * Action key for adding a child category
   */
  public static final String ADDCHILD_ACTION = "ADDCHILD";
  /**
   * Action key for adding a sibling category
   */
  public static final String ADDSIBLING_ACTION = "ADDSIBLING";
  /**
   * Action key for renaming a category
   */
  public static final String RENAME_ACTION = "RENAMENODE";
  /**
   * Action key for deleting a category
   */
  public static final String DELETE_ACTION = "DELETENODE";

  /**
   * Generated serial version UID
   */
  private static final long serialVersionUID = -9083503466128846526L;

  /**
   * Context menu constructor
   * 
   * @param category the category to manage
   * @param listener the action listener
   */
  
  public CategoryPopupMenu() {
    super();
    setBorder(new TitledBorder(""));
    JMenuItem menuItem;
    menuItem = new JMenuItem(CategoryAction.getRenameCategoryAction());
    add(menuItem);
    menuItem = new JMenuItem(CategoryAction.getAddChildCategoryAction());
    add(menuItem);
    menuItem = new JMenuItem(CategoryAction.getAddSiblingCategoryAction());
    add(menuItem);
    menuItem = new JMenuItem(CategoryAction.getDeleteCategoryAction());
    add(menuItem);
  }
  
  public void addActionListener(ActionListener listener) {
    CategoryAction.getRenameCategoryAction().addActionListener(listener);
    CategoryAction.getAddChildCategoryAction().addActionListener(listener);
    CategoryAction.getAddSiblingCategoryAction().addActionListener(listener);
    CategoryAction.getDeleteCategoryAction().addActionListener(listener);
  }
  
  public void removeActionListener(ActionListener listener) {
    CategoryAction.getRenameCategoryAction().removeActionListener(listener);
    CategoryAction.getAddChildCategoryAction().removeActionListener(listener);
    CategoryAction.getAddSiblingCategoryAction().removeActionListener(listener);
    CategoryAction.getDeleteCategoryAction().removeActionListener(listener);
  }
  
  public void prepareForNode(CategoryNode category) {
    ((TitledBorder)getBorder()).setTitle("Edit \"" + category.getName() + "\"");
    CategoryAction.getRenameCategoryAction().setEnabled(category.isEditable());
    CategoryAction.getAddChildCategoryAction().setEnabled(category != null);
    CategoryAction.getAddSiblingCategoryAction().setEnabled(category.isEditable());
    CategoryAction.getDeleteCategoryAction().setEnabled(category.isEditable());
  }
}
